package com.acmedcare.framework.exchange.center.endpoint.service;

import com.acmedcare.framework.boot.snowflake.Snowflake;
import com.acmedcare.framework.exchange.center.common.ConvertUtils;
import com.acmedcare.framework.exchange.center.common.Page;
import com.acmedcare.framework.exchange.center.endpoint.exception.InvalidRequestParameterException;
import com.acmedcare.framework.exchange.center.entity.bean.Plugin;
import com.acmedcare.framework.exchange.center.entity.dto.PluginQueryDto;
import com.acmedcare.framework.exchange.center.repository.PluginRepository;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Service
public class PluginService {

  private final PluginRepository repository;
  private final Snowflake snowflake;

  public PluginService(
      PluginRepository repository, Snowflake snowflake) {
    this.repository = repository;
    this.snowflake = snowflake;
  }

  public Page<Plugin> getList(PluginQueryDto queryDto) {

    QueryWrapper<Plugin> queryWrapper = new QueryWrapper<>();
    if (!StringUtils.isEmpty(queryDto.getName())) {

      queryWrapper.like("name", queryDto.getName());
    }

    if (queryDto.getStatusEnum() != null) {

      queryWrapper.eq("status", queryDto.getStatusEnum().toString());
    }

    PageHelper.startPage(queryDto.getCurrPage(), queryDto.getSize());

    List<Plugin> plugins = repository.selectList(queryWrapper);

    return ConvertUtils.convertPage(plugins);
  }

  public Plugin get(Long id) {

    return repository.selectById(id);
  }

  public void add(Plugin plugin) throws InvalidRequestParameterException {

    plugin.setPluginId(snowflake.nextId());
    Plugin obj = getByName(plugin.getName());

    if (obj != null) {

      throw new InvalidRequestParameterException("插件名称不允许为空!");
    }

    repository.insert(plugin);
  }

  public void update(Plugin plugin) throws InvalidRequestParameterException {

    Plugin obj = getByName(plugin.getName());
    if (obj != null && !obj.getPluginId().equals(plugin.getPluginId())) {

      throw new InvalidRequestParameterException("插件名称不允许重复!");
    }

    repository.updateById(plugin);
  }

  public Plugin getByName(String name) {

    QueryWrapper<Plugin> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("name", name);
    List<Plugin> plugins = repository.selectList(queryWrapper);
    if (plugins.isEmpty()) {
      return null;
    }

    return plugins.stream().findFirst().get();
  }

  public void delete(Long id) {

    repository.deleteById(id);
  }
}
